/**
 * Project Name:chaos-framework
 * File Name:ObjectMappingCustomer.java
 * Package Name:com.chaos.framework.comm.customer
 * Date:2015年1月28日下午5:19:22
 * Copyright (c) 2015, www.bailing.co All rights Reserved.
 */

package com.huiquan.framework.base;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.huiquan.framework.utils.JsonUtil;

/**
 * @ClassName: ObjectMappingCustomer
 * @author yangsh
 * @Description: JSON返回自定义
 * date 2015年1月28日 下午5:19:22
 * @version V1.0
 */
public class ObjectMappingCustomer extends ObjectMapper {

    private static final long serialVersionUID = 1111111111111111111L;

    private static Logger LOGGER = LoggerFactory.getLogger(ObjectMappingCustomer.class);

    /**<p>Title: .</p>
     * <p>Description: </p> 
     */
    public ObjectMappingCustomer() {
        this.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true); // 字段名加双引号
        this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, false); // 数值加双引号

        this.getSerializerProvider().setNullValueSerializer(
            new JsonSerializer<Object>() {
                @Override
                public void serialize(Object value, JsonGenerator jg,
                        SerializerProvider sp) throws IOException {
                     jg.writeString("");
                }
            }
        );
    }
    
    @Override
    public void writeValue(JsonGenerator jgen, Object value) throws IOException, JsonGenerationException, JsonMappingException {
        if (value instanceof ReturnData) {
            ReturnData rd = (ReturnData) value;

            Map<String, Object> data = rd.getData();
            
            Map<String, Object> rm = new HashMap<String, Object>();

            rm.put("code", rd.getReturnCode().getCode());
            rm.put("desc", rd.getReturnCode().getDesc());

            if (!data.isEmpty()) {
                rm.put("data", data);
            }
            
            if (!data.isEmpty()) {
            	LOGGER.debug("return data: {}", JsonUtil.toJsonStr(data));
            }

            super.writeValue(jgen, rm);
        } else {
            super.writeValue(jgen, value);
        }
    }
    
}
